const Base = require('./base.js');
const API = require('co-wechat-api');
const fs = require('fs');
module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.wxuser = this.model("weixin/user");
		this.conf = this.model("weixin/config");
	

	}
	async indexAction() {
		if(this.isGet){
			let gets = this.get();
			let wxid = "";
			let wxlist = await this.conf.select();

			if(!think.isEmpty(gets.id)) {
				let weixin = await this.conf.findOne(gets.id);
				if(!think.isEmpty(weixin)) {
					wxid = gets.id;
				}

			} else {
				if(!think.isEmpty(wxlist)) {
					wxid = wxlist[0].id;
				}

			}
			
			this.assign("wxid", wxid);
			this.assign("wxlist", wxlist);
			
			
			return this.display();
		}
		if(this.isPost){
			let posts = this.post();
			let where = {};
			
			if(!think.isEmpty(posts.wxid)){
				where.wxid = posts.wxid;
			}
			if(!think.isEmpty(posts.nickname)){
				where.nickname = ['like', '%' + posts.nickname + '%'];
			}

			const data = await this.wxuser.dataTable(posts, where);
			console.log(data)
			return this.json(data);
		}
		

	}
	
	async downAction(){
		let wxid = this.post("wxid");
		if(think.isEmpty(wxid)){
			return this.fail("同步失败,请配置公众号");
		}
		let api = await this.wechatApi(wxid);
		let followers = await api.getFollowers();
		let users = await api.batchGetUsers(followers.data.openid);
		if(think.isEmpty(users.user_info_list)){
			return this.fail("同步失败,微信帐号信息配置错误");
		}
		users.user_info_list.forEach(async (user)=>{
			user.wxid = wxid;
			user.subscribe_time = user.subscribe_time*1000;
			await this.wxuser.thenUpdate(user,{
				openid: user.openid,
				wxid: wxid
			});
			
		});
		return this.success("同步成功,请稍等几秒后刷新本页面");
		
		
	}


};